/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Department;
import com.riq.entity.Location;
import com.riq.entity.Status;

@SuppressWarnings("serial")
public class AdminLocationServlet extends HttpServlet {
  private static final Logger log = Logger.getLogger(Department.class.getName());

  private Long deptId;
  
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException { 
    doGet(request, response);
  }
  
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  // ---------------------------------------------------------------------------------------------
  //  HEADER: LOCATION
  // ---------------------------------------------------------------------------------------------

    Cookie[] cookie = request.getCookies();
    deptId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvDeptId", "99999"));
    
    String action = request.getParameter("action"); 
    
  // ---------------------------------------------------------------------------------------------
  //  METHOD DIRECTORY
  // ---------------------------------------------------------------------------------------------

    if ("prepCreate".equalsIgnoreCase(action)) {
      prepCreate(response, request); 
     } else if ("create".equalsIgnoreCase(action)) { 
      create(response, request); 
    } else if ("display".equalsIgnoreCase(action)) { 
      display(response, request);
    } else if ("edit".equalsIgnoreCase(action)) { 
      edit(response, request); 
    } else if ("set".equalsIgnoreCase(action)) { 
      set(response, request); 
    } else if ("delete".equalsIgnoreCase(action)) { 
      delete(response, request); 
    } 
    
  }

  // -----------------------------------------------------------------------------------------------
  //  METHODS
  // -----------------------------------------------------------------------------------------------


  private void prepCreate(HttpServletResponse response, ServletRequest request) 
     throws ServletException, IOException {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Department d = pm.getObjectById(Department.class, deptId);

    String qStatus = "select from " + Status.class.getName() + 
    " where deptId == " + deptId + " order by type asc, shortName asc";
    List<Status> statuses = (List<Status>) pm.newQuery(qStatus).execute();

  	request.setAttribute("statuses", statuses);
    request.setAttribute("dept", d);

	  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/locationCreate.jsp?" + 
	        "deptId=" + deptId.toString());
	  dispatcher.forward(request, response);	
  }

  
  private void create(HttpServletResponse response, ServletRequest request) {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Long gpsTimeStamp = null;
    Double distance = null;
    Long targetObjectId = null;
    String targetObjectType = null;
    Long timeStamp = System.currentTimeMillis();
    String vru = "";
    String gpsAccuracy = "";
    String special = "";

  	String sequence = request.getParameter("sequence");
  	int seq = new Integer(sequence).intValue();
  	
    Location l = new Location (
      deptId,
      request.getParameter("shortName"),
      request.getParameter("longName"),
      request.getParameter("type"),
      request.getParameter("special"),
      seq,
      request.getParameter("vru"),
      timeStamp,
      request.getParameter("lastLat"),
      request.getParameter("lastLng"),
      gpsTimeStamp,
      gpsAccuracy,
      request.getParameter("latitudeId"),
      targetObjectId,
      targetObjectType,
      request.getParameter("position"),
      distance,
      null,
      null
    );
    pm.makePersistent(l);
    
    
    Enumeration paramNames = request.getParameterNames();
    while(paramNames.hasMoreElements()) {
      String paramName = (String)paramNames.nextElement();
      String[] paramValues = request.getParameterValues(paramName);
      if (paramValues.length >= 1) {
        if (paramName.equalsIgnoreCase("statusId")) {
          for (int i=0; i < paramValues.length; i++) {  
            Long memberValue = Long.valueOf(paramValues[i]);
            Status s = pm.getObjectById(Status.class, memberValue);
            l.addStatus(s);
            pm.makePersistent(l);
          } 
        }
      }
    }
    
    pm.close();
  	  
  	RequestDispatcher dispatcher = 
  	  getServletContext().getRequestDispatcher("/department?action=display");
  	
  	try
  	{
  	  dispatcher.forward(request, response);
  	} catch (ServletException e)
  	{
  	  // TODO Auto-generated catch block
  	  e.printStackTrace();
  	} catch (IOException e)
  	{
  	  // TODO Auto-generated catch block
  	  e.printStackTrace();
  	}  
 }

  /**
   * Returns a list of Status objects from a set of Status keys.
   * Initializes s with an array to avoid null pointer exceptions if no keys are sent
   * or the query result is null.
   * @param keys
   * @return
   */
  public List<Status> getById(Set<Long> keys) { 
    
    List<Status> s = new ArrayList<Status>();
    if (keys.size() > 0) {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    javax.jdo.Query q = pm.newQuery("select from " + Status.class.getName() + 
        " where key == :keys"); 
    s = (List<Status>) q.execute(keys); 
    }
    return s;   
  }
	    
  
  private void display(HttpServletResponse response, ServletRequest request) {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Long locationId = Long.valueOf(request.getParameter("locationId"));
    Location l = (Location) pm.getObjectById(Location.class, locationId);
    request.setAttribute("location", l);
    
    List<Status> s;
    s = getById(l.getstatusKeys());
    request.setAttribute("selectedStatuses", s);
    
    Department d = pm.getObjectById(Department.class, l.getdeptId());
    request.setAttribute("dept", d);
    System.out.println("display deptId = " + d.getid().toString());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/locationDisplay.jsp");
    try
    {
      dispatcher.forward(request, response);
    } catch (ServletException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }

  
  private void edit(HttpServletResponse response, ServletRequest request) {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Long locationId = Long.valueOf(request.getParameter("locationId"));

    Location l = pm.getObjectById(Location.class, locationId);	
    request.setAttribute("location", l);
    
    Department d = pm.getObjectById(Department.class, l.getdeptId());
    request.setAttribute("dept", d);
    
    String queryStatus = "select from " + Status.class.getName() + 
    " where deptId == " + l.getdeptId() + " order by type asc, shortName asc";
    List<Status> allStatuses = (List<Status>) pm.newQuery(queryStatus).execute();
    request.setAttribute("allStatuses", allStatuses);
    
    List<Status> selectedStatuses = getById(l.getstatusKeys());
    List<Long> selectedStatusIds = new ArrayList<Long>();
    for (Status s : selectedStatuses) {
      selectedStatusIds.add(s.getid());
    }
    request.setAttribute("selectedStatuses", selectedStatusIds);


    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/locationEdit.jsp");
    try
    {
      dispatcher.forward(request, response);
    } catch (ServletException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  
  private void set(HttpServletResponse response, ServletRequest request) {

    PersistenceManager pm = PMF.get().getPersistenceManager();

    Long locationId = Long.valueOf(request.getParameter("locationId"));
    Location l = pm.getObjectById(Location.class, locationId); 
   
    String sequence = request.getParameter("sequence");
    int seq = new Integer(sequence).intValue();

    // set values
    l.setdeptId(Long.valueOf(request.getParameter("deptId")));
    l.setshortName(request.getParameter("shortName"));
    l.setlongName(request.getParameter("longName"));
    l.settype(request.getParameter("type"));
    l.setsequence(seq); 
    l.setposition(request.getParameter("position"));
    l.setlastLat(request.getParameter("lastLat"));
    l.setlastLng(request.getParameter("lastLng"));
    l.setlatitudeId(request.getParameter("latitudeId"));
    l.setspecial(request.getParameter("special"));
    l.setvru(request.getParameter("vru"));
    
    l.setstatusKeys(null); // purge previous selections, replace with new from form
    pm.makePersistent(l); 

    Enumeration paramNames =  (Enumeration) request.getParameterNames();
    List<Status> statuses = new ArrayList<Status>();
    if (paramNames != null) {
      while(paramNames.hasMoreElements()) {
        String paramName = (String)paramNames.nextElement();
        String[] paramValues = (String[])(request.getParameterValues(paramName));
        if (paramValues.length >= 1) {
          if (paramName.equalsIgnoreCase("statusId")) {
            for (int i=0; i < paramValues.length; i++) {
              if (!(paramValues[i].equals(""))) {
                Status s = pm.getObjectById(Status.class, Long.valueOf(paramValues[i]));
                statuses.add(s);
                System.out.println("paramValue for status: " + paramValues[i]);
               }
            } 
          }
        }
      }
    }
    
    
    System.out.println("total inbound selected statuses for location from edit page: " + 
        statuses.size());
    if (statuses != null) {
      for (Status s2 : statuses) {
        l.addStatus(s2);
      }
    }
    
    pm.makePersistent(l); 
    pm.close();
    
    RequestDispatcher dispatcher = 
  	  getServletContext().getRequestDispatcher("/department?action=display");
    try
    {
      dispatcher.forward(request, response);
    } catch (ServletException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }  
  }
  

  
  private void delete(HttpServletResponse response, ServletRequest request) {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Long locationId = Long.valueOf(request.getParameter("locationId"));
    Location l = pm.getObjectById(Location.class, locationId);
    pm.deletePersistent(l);
    try
    {
      response.sendRedirect("department?action=display");
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }


 
}

